<template>
  <div>
    <FormPanel ref="from"
               :list="formList"
               @formChange="changeHandle"
               :isSubmitBtn="false"
               :collapse="false"
               :labelWidth="110"></FormPanel>

    <FilterTable ref="table"
                 :columns="columns"
                 :dataSource="tableList"
                 height="auto"
                 :onColumnsChange="(columns) => (this.columns = columns)">
    </FilterTable>

    <div style="height: 47px"></div>
    <div :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right',
      }">
      <el-button @click="closeDrawer">关 闭</el-button>
    </div>
  </div>
</template>
<script>

import {
  getAmount,
  getDealerAddress,
  getSelfAddress,
  getDetail,
  getFiAccountType,
  getOrderDetailType
} from '@/api/omSaleP/OrderManagement/OrderImport/index.js';
import {dictionary} from '@/utils/dictMixin';
import moment from 'moment';

export default {
  mixins: [dictionary],
  components: {},
  props: ['rowData'],
  data() {
    this.saveData = null;
    return {
      formList: this.createdFrom(),
      columns: this.createdTable(),
      tableList: [],
      isaddCar: false,
      orderData: {},
      json: {},
      dealerCode: '',
      orderDetailTypeList: [],
      addressList: [],
      selfAddress: [],
      accountTypeList: [],
      totalAmount: [],
      selectList: [],
      isDisabled: true
    };
  },
  created() {
    // 初始化
    this.initOrder();
  },
  mounted() {
    this.table = this.$refs.table.$refs.pageTable;
  },
  methods: {
    createdFrom() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '订单信息',
        },
        {
          type: 'INPUT',
          label: '订单编号',
          fieldName: 'orderNo',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'DATE',
          label: '订单年月',
          fieldName: 'orderYearMonth',
          disabled: true,
          placeholder: '请输入',
          dateType: 'month',
          initialValue: moment().format('YYYY-MM'),
        },
        {
          type: 'INPUT',
          label: '订单经销商',
          fieldName: 'dealerCode',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '订单类型',
          fieldName: 'orderType',
          disabled: true,
          placeholder: '请选择',
          itemList: this.createDictList('2105'),
          initialValue: 21051002, // 默认增补订单
        },
        {
          type: 'SELECT',
          label: '订单细分类型',
          fieldName: 'orderDetailType',
          placeholder: '请选择',
          itemList: [],
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '订单状态',
          fieldName: 'orderStatus',
          disabled: true,
          placeholder: '请选择',
          itemList: this.createDictList('2104'),
          initialValue: 21041001, // 默认新建
        },
        {
          type: 'SELECT',
          label: '订单紧急度',
          fieldName: 'emergencyType',
          placeholder: '请选择',
          itemList: this.createDictList('2101'),
          initialValue: 21011001,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '运输方式',
          fieldName: 'transportType',
          placeholder: '请选择',
          itemList: this.createDictList('2409'),
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '收车地址',
          fieldName: 'addressId',
          placeholder: '请选择',
          itemList: [],
          disabled: true,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          change: (value) => {
            this.orderAddressOnChange(value);
          },
        },
        {
          type: 'INPUT',
          label: '送达城市',
          fieldName: 'orderCity',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '联系人',
          fieldName: 'linkMan',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '联系电话',
          fieldName: 'linkPhone',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'INPUT',
          numberFormat: true,
          initialValue: 0.00,
          label: '资金可用余额',
          fieldName: 'totalFuelAmount',
          placeholder: '请选择',
          disabled: true
        },
        {
          type: 'INPUT',
          numberFormat: true,
          initialValue: 0.00,
          label: '返利池可用余额',
          fieldName: 'singleRebateFuelAmount',
          disabled: true
        },
        {
          type: 'INPUT',
          numberFormat: true,
          initialValue: 0.00,
          label: '本单返利使用金额',
          fieldName: 'singleRebateFuelTotalAmount',
          disabled: true
        },
        {
          type: 'INPUT',
          numberFormat: true,
          initialValue: 0.00,
          label: '实付总金额',
          fieldName: 'realPayTotalAmount',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '创建人',
          fieldName: 'createdName',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '创建时间',
          fieldName: 'createdAt',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'BREAK_SPACE',
          label: '车辆信息',
        },
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '物料编码',
          dataIndex: 'productCode',
          width: 200,
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '物料描述',
          dataIndex: 'productName',
          width: 400,
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '提报数量',
          dataIndex: 'orderNum',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: 150,
          editable: false,
          editType: 'number',
          editRequired: true,
          defaultEditable: true,
          editPattern: /^[1-9]\d*$/,
          summation: true,
          rules: [{required: true, message: '请填写正整数', trigger: 'blur'}],
        },
        {
          title: '车辆用途',
          dataIndex: 'vehicleUse',
          width: 150,
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: false,
          editType: 'select',
          editRequired: true,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          render: (p) => {
            return (
                <el-select
                    size="mini"
                    v-model={p.row.vehicleUse}
                    placeholder="请选择"
                    disabled
                >
                  {this.createDictList('2102').map((item) => (
                      <el-option key={item.value} label={item.text} value={item.value}/>
                  ))}
                </el-select>
            );
          },
        },
        {
          title: '资金类型',
          dataIndex: 'fundType',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: false,
          editType: 'select',
          editRequired: true,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          render: (p) => {
            return (
                <el-select
                    size="mini"
                    v-model={p.row.fundType}
                    required
                    placeholder="请选择"
                    disabled
                >
                  {this.accountTypeList.map((item) => (
                      <el-option key={item.accountId} label={item.accountTypeName} value={item.accountId}/>
                  ))}
                </el-select>
            );
          },
        },
        {
          title: '价格类型',
          dataIndex: 'amountType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2136'),
          render: (p) => {
            return <span>{this.createDictText(p.row.amountType, '2136')}</span>;
          },
        },
        {
          title: '采购价格',
          dataIndex: 'afterDiscountAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          numberFormat: true,
          precision: 2,
          align: "right"
        },
        {
          title: '市场指导价',
          dataIndex: 'singleAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          numberFormat: true,
          precision: 2,
          align: "right"
        },
        {
          title: '现金折让',
          dataIndex: 'discountAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          numberFormat: true,
          precision: 2,
          align: "right"
        },
        {
          title: '建店返利',
          dataIndex: 'buildRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          numberFormat: true,
          precision: 2,
          align: "right"
        },
        {
          title: '是否使用返利',
          dataIndex: 'isRebate',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: false,
          editType: 'select',
          editRequired: true,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          render: (p) => {
            return (
                <el-select
                    size="mini"
                    v-model={p.row.isRebate}
                    placeholder="请选择"
                    disabled
                >
                  {this.createDictList('1004').map((item) => (
                      <el-option key={item.value} label={item.text} value={item.value}/>
                  ))}
                </el-select>
            );
          },
        },
        {
          title: '返利冲抵',
          dataIndex: 'singleRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          numberFormat: true,
          precision: 2,
          align: "right"
        },
        {
          title: '车系',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '配置',
          dataIndex: 'packageName',
          width: 300,
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '选装',
          dataIndex: 'optionName',
          width: 200,
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '内饰',
          dataIndex: 'trimName',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input',
        }
      ];
    },
    changeHandle(val) {
      this.saveData = val;
    },
    /**
     * 初始化
     */
    async initOrder() {
      this.dealerCode = this.rowData.dealerCode;

      // 订单细分类型
      await this.getOrderDetailType();
      // 收车地址
      await this.getDealerAddress(this.dealerCode);
      // 自提地址
      await this.getSelfAddress();
      // 资金类型
      await this.getFiAccountType(this.dealerCode);
      // 经销商资金
      await this.getTotalAmount(this.dealerCode);

      // 通过订单id查询订单和订单明细数据
      let res = await getDetail({orderId: this.rowData.orderId});
      if (res.resultCode === 200) {
        let addressId = null;
        for (let i in res.data) {
          this.formList.map(x => {
            if (i === x.fieldName) {
              x.initialValue = res.data[i];
            }
            // 订单细分类型
            if (x.fieldName === 'orderDetailType') {
              x.itemList = this.orderDetailTypeList.map(x => ({text: x.subName, value: x.subId}));
            }
            // 运输方式
            if (x.fieldName === 'transportType') {
              this.transportTypeOnChange(x.initialValue);
            }
            // 收车地址
            if (i === 'addressId') {
              addressId = res.data[i];
            }
            // 经销商资金
            if (x.fieldName === 'totalFuelAmount') {
              x.initialValue = this.formatNumber(this.totalAmount.totalFuelAmount);
            }
            if (x.fieldName === 'singleRebateFuelAmount') {
              x.initialValue = this.formatNumber(this.totalAmount.singleRebateFuelAmount);
            }
          });
        }

        // 赋值收车地址信息
        if (addressId !== null) {
          await this.orderAddressOnChange(addressId);
        }
        // 明细
        this.tableList = res.data.detailDTOList || [];
        for (const car of this.tableList) {
          await this.reComputedAmount(car);
        }
      }
    },
    /**
     * 获取订单细分类型
     */
    async getOrderDetailType() {
      let res = await getOrderDetailType({isAvailable: 10041001});
      if (res.resultCode === 200) {
        this.orderDetailTypeList = res.data;
      }
    },
    /**
     * 获取收车地址
     */
    async getDealerAddress(dealerCode) {
      let res = await getDealerAddress({dealerCode: dealerCode});
      if (res.resultCode === 200) {
        this.addressList = res.data;
      }
    },
    /**
     * 自提地址
     */
    async getSelfAddress() {
      let res = await getSelfAddress();
      if (res.resultCode === 200) {
        this.selfAddress = res.data;
      }
    },
    /**
     * 选择运输方式
     */
    async transportTypeOnChange(value) {
      this.formList.find(item => item.fieldName === 'addressId').initialValue = '';
      this.formList.find(item => item.fieldName === 'orderCity').initialValue = '';
      this.formList.find(item => item.fieldName === 'linkMan').initialValue = '';
      this.formList.find(item => item.fieldName === 'linkPhone').initialValue = '';
      if (24091002 === value) {
        // 自提
        this.formList.find(item => item.fieldName === 'addressId').itemList = [];
        for (let i in this.selfAddress) {
          if (this.selfAddress[i] !== null && this.selfAddress[i].addressId !== null &&
              typeof (this.selfAddress[i].addressId) !== "undefined") {
            // 添加到收车地址下拉
            this.formList.find(item => item.fieldName === 'addressId').itemList.push({
              text: this.selfAddress[i].address,
              value: this.selfAddress[i].addressId
            });
          }
        }
        // 默认第一条收车地址
        if (this.selfAddress[0] !== null && typeof (this.selfAddress[0]) !== "undefined") {
          this.formList.find(item => item.fieldName === 'addressId').initialValue = this.selfAddress[0].addressId;
          this.formList.find(item => item.fieldName === 'orderCity').initialValue = this.selfAddress[0].cityName;
          this.formList.find(item => item.fieldName === 'linkMan').initialValue = this.selfAddress[0].linkMan;
          this.formList.find(item => item.fieldName === 'linkPhone').initialValue = this.selfAddress[0].linkPhone;
        }
      } else if (24091001 === value) {
        // 经销商收车地址
        this.formList.find(item => item.fieldName === 'addressId').itemList = [];
        (this.addressList || []).map(x => {
          this.formList.find(item => item.fieldName === 'addressId').itemList.push({
            text: x.address,
            value: x.addressId
          });
        });
        // 获取主店收车地址
        let indexAddress = 0;
        for (let i in this.addressList) {
          if (this.addressList[i].addressProperty === 60351001) {
            indexAddress = i;
            break;
          }
        }
        // 未获取到主店收车地址则默认第一条
        if (this.addressList[indexAddress] !== null && typeof (this.addressList[indexAddress]) !== "undefined") {
          this.formList.find(item => item.fieldName === 'addressId').initialValue = this.addressList[indexAddress].addressId;
          this.formList.find(item => item.fieldName === 'orderCity').initialValue = this.addressList[indexAddress].cityName;
          this.formList.find(item => item.fieldName === 'linkMan').initialValue = this.addressList[indexAddress].linkMan;
          this.formList.find(item => item.fieldName === 'linkPhone').initialValue = this.addressList[indexAddress].linkPhone;
        }
      }
    },
    /**
     * 根据运输方式获取收车地址
     * @returns {[]}
     */
    getAddressByTransportType() {
      let addressListTemp = [];
      const transportType = this.formList.find(item => item.fieldName === 'transportType').initialValue;
      if (transportType === 24091002) {
        // 自提
        addressListTemp = this.selfAddress;
      } else if (transportType === 24091001) {
        addressListTemp = this.addressList;
      }
      return addressListTemp;
    },
    /**
     * 选择收车地址事件
     */
    async orderAddressOnChange(value) {
      this.formList.find(item => item.fieldName === 'addressId').initialValue = '';
      this.formList.find(item => item.fieldName === 'linkMan').initialValue = '';
      this.formList.find(item => item.fieldName === 'orderCity').initialValue = '';
      this.formList.find(item => item.fieldName === 'linkPhone').initialValue = '';

      this.getAddressByTransportType().map(address => {
        if (address.addressId === value) {
          this.formList.find(item => item.fieldName === 'addressId').initialValue = address.addressId;
          this.formList.find(item => item.fieldName === 'orderCity').initialValue = address.cityName;
          this.formList.find(item => item.fieldName === 'linkMan').initialValue = address.linkMan;
          this.formList.find(item => item.fieldName === 'linkPhone').initialValue = address.linkPhone;
        }
      });
    },
    /**
     * 查询经销商资金可用余额和返利池可用余额
     */
    async getTotalAmount(dealerCode) {
      let res = await getAmount({dealerCode: dealerCode});
      if (res.resultCode === 200) {
        this.totalAmount = res.data;
      }
    },
    /**
     * 查询资金类型
     */
    async getFiAccountType(dealerCode) {
      let res = await getFiAccountType({dealerCode: dealerCode});
      if (res.resultCode === 200) {
        this.accountTypeList = res.data;
      }
    },
    /**
     * 获取三方资金类型
     */
    getThreePartyAccountType() {
      let accountId = null;
      let index = 0;
      for (let i in this.accountTypeList) {
        // 60051001 : 三方资金类型
        if (this.accountTypeList[i].accountType === 60051001) {
          index = i;
          break;
        }
      }
      if (this.accountTypeList[index]) {
        accountId = this.accountTypeList[index].accountId;
      }
      return accountId;
    },
    /**
     * 计算价格
     * @param car 当前车辆数据
     * @returns {Promise<void>}
     */
    async reComputedAmount(car) {
      car.afterDiscountAmount = this.formatNumber(car.afterDiscountAmount);
      car.discountAmount = this.formatNumber(car.discountAmount);
      car.buildRebateAmount = this.formatNumber(car.buildRebateAmount);
      car.singleRebateAmount = this.formatNumber(car.singleRebateAmount);
      car.singleRebateAmountOrg = this.formatNumber(car.singleRebateAmountOrg);

      this.$forceUpdate();
      this.reComputedAmountTotal();
    },
    reComputedAmountTotal() {
      // 本单返利使用金额
      let singleRebateFuelTotalAmount = 0.0;
      // 实付总金额
      let realPayTotalAmount = 0.0;

      this.tableList.forEach(async car => {
        singleRebateFuelTotalAmount += car.singleRebateAmount * car.orderNum;
        realPayTotalAmount += car.afterDiscountAmount * car.orderNum;
      });

      this.formList.map(x => {
        if (x.fieldName === 'singleRebateFuelTotalAmount') {
          x.initialValue = this.formatNumber(singleRebateFuelTotalAmount);
        }
        if (x.fieldName === 'realPayTotalAmount') {
          x.initialValue = this.formatNumber(realPayTotalAmount);
        }
      });
    },
    selectChangeHandle(rows) {
      this.selectList = rows;
    },
    async closeDrawer() {
      this.$emit('close');
    },
    formatNumber(val) {
      return Number(val).toFixed(2);
    }
  },
};
</script>
<style lang="less">
.discount {
  text-decoration: underline;
  color: #d1291a;
  cursor: pointer;
}
</style>
